import { dealFn } from "../static/mapline.js"
import { seriesPoint } from "./option.js"
const { echarts } = window;

let judData = (data) => Object.prototype.toString.call(data).slice(8, -1);

let initArea = {
  type: 'custom',
  coordinateSystem: 'bmap',
  renderItem: () => {},
  itemStyle: {
    normal: {
      opacity: 0.5
    }
  },
  animation: false,
  silent: true,
  data: [0],
  z: -10
}

function deepObj(source) {
  let result = source instanceof Array ? [] : {};
  for (let key in source) {
    result[key] = typeof source[key] === 'object' ? deepObj(source[key]) : source[key];
  }
  return result;
}

function setKeys(oldkey, newkey) {
  for (let key in newkey) {
    oldkey[key] = newkey[key];
  }
}

function dealPointArr(data) {
  return data.map((item) => {
    let newarr = [];
    if (item.longitude && item.latitude) {
      newarr.push(item.longitude)
      newarr.push(item.latitude)
    }
    return newarr
  })
}
/**
 * @author
 * @param coords [] 内含数据坐标值
 * @description  就后天传入的坐标数据进行处理。 之后返回，参数中 Serise 的单个体。经纬度所连为矩形
 * @return option 中 Serise 中的 {}
 */
function sumQuare(data) {
  let pointObj = {
    longitudeBig: 0, //维度的最大值
    longitudeLit: 0, //维度的最小值
    latitudeBig: 0,  //经度的最大值
    latitudeLit: 0  //经度的最小值
  };
  let firstUse = false; //用于判断遍历的是否是第一个。
  data.forEach((item) => {
    let longitude = Number(item.longitude);
    let latitude = Number(item.latitude);
    if (!firstUse) {
      pointObj.longitudeBig = longitude;
      pointObj.longitudeLit = longitude;
      pointObj.latitudeBig = latitude;
      pointObj.latitudeLit = latitude;
      firstUse = true;
    }
    if (latitude > pointObj.latitudeBig) {
      pointObj.latitudeBig = latitude;
    } else if (latitude < pointObj.latitudeLit) {
      pointObj.latitudeLit = latitude;
    }
    if (longitude > pointObj.longitudeBig) {
      pointObj.longitudeBig = longitude;
    } else if (longitude < pointObj.longitudeLit) {
      pointObj.longitudeLit = longitude;
    }
  })
  let longitudeUnit = (pointObj.longitudeBig - pointObj.longitudeLit)/3;
  let latitudeUnit = (pointObj.latitudeBig - pointObj.latitudeLit) / 3;
  // 正方形数据
  let newArr = [
    [pointObj.longitudeBig, pointObj.latitudeBig],
    [pointObj.longitudeBig, pointObj.latitudeLit],
    [pointObj.longitudeLit, pointObj.latitudeLit],
    [pointObj.longitudeLit, pointObj.latitudeBig]
  ];
  // 八角形数据
  let newMyArr = [
    [pointObj.longitudeLit + longitudeUnit, pointObj.latitudeLit],
    [pointObj.longitudeLit + (2 * longitudeUnit), pointObj.latitudeLit],
    [pointObj.longitudeBig, pointObj.latitudeLit + latitudeUnit],
    [pointObj.longitudeBig, pointObj.latitudeLit + (2 * latitudeUnit)],
    [pointObj.longitudeLit + (2 * longitudeUnit), pointObj.latitudeBig],
    [pointObj.longitudeLit + longitudeUnit, pointObj.latitudeBig],
    [pointObj.longitudeLit, pointObj.latitudeLit + (2 * latitudeUnit)],
    [pointObj.longitudeLit, pointObj.latitudeLit + latitudeUnit]
  ]
  return newMyArr;
}
/**
 * @author
 * @param coords [[], [], []] 内含数据坐标值
 * @description  就后天传入的坐标数据按顺序连接。 之后返回，参数中 Serise 的单个体。经纬度按顺序连接。
 * @return option 中 Serise 中的 {}
 */
function setSerise({ coords = [] }) {
  let newSerise = deepObj(seriesPoint);
  let renderItem = (params, api) => {
    var points = [];
    for (var i = 0; i < coords.length; i++) {
      points.push(api.coord(coords[i]));
    }
    var color = api.visual('color');
    return {
      type: 'polygon',
      shape: {
        points: echarts.graphic.clipPointsByRect(points, {
          x: params.coordSys.x,
          y: params.coordSys.y,
          width: params.coordSys.width,
          height: params.coordSys.height
        })
      },
      style: api.style({
        fill: color,
        stroke: echarts.color.lift(color)
      })
    };
  }
  newSerise.renderItem = renderItem
  return newSerise;
}

/**
 * @author
 * @param 
 * @description  设定点的信息
 * @return option 中 Serise 中的 {}
 */
function convertData(data) {
  var serise = [];
  for (var i = 0; i < data.length; i++) {
    let itudeAll = (data[i].longitude && data[i].latitude) ? [data[i].longitude, data[i].latitude, { val: 10, use: 15}] : [];
    if (itudeAll.length) {
      serise.push({
        name: data[i].cityname,
        data: data[i],
        value: itudeAll
      });
    }
  }
  return serise;
};
function setPointSerise({ data = [], symbolSize = 10, name = "Top 5", color = '#f4e925', labelShow = true }) {
  return {
    name: name,
    tooltip: {
      formatter: function (params) {
        let { data } = params;
        let itemdata = data.data;
        return `
          ${params.name}<br/>
          仓储成本：${itemdata.warehousingCost} 万元<br/>
          仓储面积：${itemdata.acreage} 平米<br/>
          重    量：${itemdata.weight} 吨
        `
      }
    },
    type: 'effectScatter',
    coordinateSystem: 'bmap',
    data: convertData(data),
    symbolSize: function (val) {
      return symbolSize
    },
    showEffectOn: 'emphasis',
    rippleEffect: {
      brushType: 'stroke'
    },
    hoverAnimation: true,
    label: {
      normal: {
        position: 'right',
        show: labelShow
      }
    },
    itemStyle: {
      normal: {
        color: color,
        shadowBlur: 10,
        shadowColor: '#333'
      }
    },
    zlevel: 1
  }
}
function setLineSerise({ data = [], colors= 'rgb(200, 35, 45)', widths=2 }) {
  return {
    type: 'lines',
    coordinateSystem: 'bmap',
    polyline: false,
    data: data,
    silent: false, //线是否可以交互
    effect: {
      show: true,
      period: 6,
      trailLength: 0.1,
      symbol:'arrow',
      symbolSize: 6
    },
    label: {
      normal: {
        formatter: '{b}',
        position: 'right',
        show: true
      }
    },
    lineStyle: {
      normal: {
        color: colors,
        opacity: .5,
        width: widths
      }
    },
    progressiveThreshold: 500,
    progressive: 200
  }
}
function dealLineData({clusterCenter, areaPoints}) {
  return areaPoints.map((item) => {
    return {
      fromName: `里程：${item.weight}； 时效：${item.transportCost}；运输成本：`,
      val: item.weight,
      coords: [[clusterCenter.longitude, clusterCenter.latitude], [item.longitude, item.latitude]]
    }
  })
}

function addChinaCenterFn({ clusterWarehousing = [] }) {
  return clusterWarehousing.map((item) => {
    return item.clusterCenter
  })
}

/**
 * @author
 * @param option {} 基础 option
 * @description  将最初的配置进行修饰。
 * @return option {} 经处理的 option。
 */
function dealOption({ option = {}, title = null, clusterWarehousing, clusterCenterChina = {
  "cityname": "哈尔滨市",
  "latitude": "45.8",
  "longitude": "126.53"
}, callback = () => { } }) {
  let newOption = deepObj(option);
  let clusterCenterAll = []; //所有的 clusterCenter数据
  let areaPointsAll = [];
  let linesAll = [];
  if (title) setKeys(newOption.title, title); //设置 title 部分。
  let areaChinaPoints = addChinaCenterFn({ clusterWarehousing });  //处理整合全国线数据
  console.log(areaChinaPoints, 'areaChinaPoints');
  let dealAllChinaCenterArr = dealLineData({ clusterCenter: clusterCenterChina, areaPoints: areaChinaPoints }); //加入全国的线数据的处理。
  newOption.series.push(setLineSerise({ data: dealAllChinaCenterArr, colors: 'orange', widths: 3}));
  clusterWarehousing.forEach((item) => {
    let { clusterCenter, areaPoints } = item;
    let dealLineDataArr = dealLineData({ clusterCenter, areaPoints }); //加入区域线数据的处理。
    clusterCenter && clusterCenterAll.push(clusterCenter);
    areaPoints && areaPointsAll.push(areaPoints);
    // let mypoint = dealPointArr(item.areaPoints); // 按顺序连接点。
    let mypoint = sumQuare(areaPoints); //连线为矩形。
    newOption.series.push(setSerise({ coords: mypoint }));
    newOption.series.push(setSerise({ coords: mypoint }));
    newOption.series.push(setLineSerise({ data: dealLineDataArr}));
  })
  areaPointsAll.forEach((item) => {
    newOption.series.push(setPointSerise({ data: item, symbolSize: 10, color: '#ddb926', labelShow: false }));
  })

  newOption.series.push(setPointSerise({ data: clusterCenterAll, name: '陕西大区', symbolSize: 20 }));

  callback(newOption);
  return newOption;
}



export { dealOption }
